package com.le.buddha.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.StreamInputTts;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsListener;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsResponse;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.le.buddha.common.BusinessRuntimeException;
import com.le.buddha.common.ResultCode;
import com.le.buddha.common.cosyvoice.GuoleCosyVoiceB;
import com.le.buddha.common.cosyvoice.GuoleCosyVoiceDemo;
import com.le.buddha.service.IAliYunService;
import com.le.buddha.service.IVoiceService;
import com.le.buddha.service.IFileService;
import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionRequest;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.ByteBuffer;
import java.util.Base64;

/**
 * 阿里音色服务实现
 *
 * @author guole
 * @created 2024/10/5
 */
@ConditionalOnProperty(name = "voiceService", havingValue = "ali")
@Service
@Slf4j
public class AliCosyVoiceServiceImpl implements IVoiceService {
    @Resource
    private IAliYunService aliYunService;
    @Value("${aliyun.appKey}")
    private String appKey;


    private NlsClient nlsClient = null;
    private IAcsClient iAcsClient = null;


    @Override
    public byte[] textToSpeech(String text, String cosyVoiceName, Integer speech) {
        StreamInputTts synthesizer = null;
        GuoleCosyVoiceB b = new GuoleCosyVoiceB();
        byte[] speechByte = null;
        try {


            synthesizer = new StreamInputTts(getNlsClient(), getSynthesizerListener(b));
            synthesizer.setAppKey(appKey);
            //设置返回音频的编码格式。
            synthesizer.setFormat(OutputFormatEnum.MP3);
            //设置返回音频的采样率。
            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_24K);
            synthesizer.setVoice(cosyVoiceName);
            //音量，范围是0~100，可选，默认50。
            synthesizer.setVolume(50);
            //语调，范围是-500~500，可选，默认是0。
            synthesizer.setPitchRate(0);
            //语速，范围是-500~500，默认是0。
            synthesizer.setSpeechRate(speech);
            //此方法将以上参数设置序列化为JSON发送给服务端，并等待服务端确认。
            synthesizer.startStreamInputTts();

            //发送流式文本数据。
            synthesizer.sendStreamInputTts(text);
            //通知服务端流式文本数据发送完毕，阻塞等待服务端处理完成
            synthesizer.stopStreamInputTts();
            speechByte = b.getSpeechByte();

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessRuntimeException("500", "阿里云语音生成异常");

        } finally {
            if (null != synthesizer) {
                synthesizer.close();
            }
        }


        return speechByte;
    }

    @Override
    public String cloneVoice(String voiceName, String fileUrl) throws Exception {

        CommonRequest cloneRequest = buildRequest("CosyVoiceClone");
        cloneRequest.putBodyParameter("VoicePrefix", voiceName);
        cloneRequest.putBodyParameter("Url", fileUrl);
        // 设定等待超时时间为60s
        cloneRequest.setSysReadTimeout(60000);
        String response = sendRequest(cloneRequest);
        JSONObject responseJson = JSON.parseObject(response);
        if (responseJson.getString("Code").equals("20000000")) {
            return responseJson.getString("VoiceName");
        }
        log.info("cloneVoice-response---" + response);

        return null;
    }

    private StreamInputTtsListener getSynthesizerListener(GuoleCosyVoiceB b) {
        StreamInputTtsListener listener = null;
        try {
            listener = new StreamInputTtsListener() {


                private boolean firstRecvBinary = true;

                //流式文本语音合成开始
                @Override
                public void onSynthesisStart(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus());
                }

                //服务端检测到了一句话的开始
                @Override
                public void onSentenceBegin(StreamInputTtsResponse response) {

                }

                //服务端检测到了一句话的结束，获得这句话的起止位置和所有时间戳
                @Override
                public void onSentenceEnd(StreamInputTtsResponse response) {


                }

                //流式文本语音合成结束
                @Override
                public void onSynthesisComplete(StreamInputTtsResponse response) {
                    // 调用onSynthesisComplete时，表示所有TTS数据已经接收完成，所有文本都已经合成音频并返回。
                    System.out.println("name: " + response.getName() + ", status: " + response.getStatus());
                    //  audioPlayer.stop();
                }

                //收到语音合成的语音二进制数据
                @Override
                public void onAudioData(ByteBuffer message) {
                    b.addByte(message);
                }

                //收到语音合成的增量音频时间戳
                @Override
                public void onSentenceSynthesis(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus() + ", subtitles: " + response.getObject("subtitles"));
                }

                @Override
                public void onFail(StreamInputTtsResponse response) {
                    // task_id是调用方和服务端通信的唯一标识，当遇到问题时，需要提供此task_id以便排查。
                    System.out.println(
                            "session_id: " + getStreamInputTts().getCurrentSessionId() +
                                    ", task_id: " + response.getTaskId() +
                                    //状态码
                                    ", status: " + response.getStatus() +
                                    //错误信息
                                    ", status_text: " + response.getStatusText());
                    // audioPlayer.stop();
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listener;
    }


    @Override
    public String speechToText(byte[] file) {
        String resultTxt="";
        try {
            byte[] bytes=file;
            String data=Base64.getEncoder().encodeToString(bytes);
            Credential cred = new Credential("AKIDJVXQ6ZqdEb0FKG1c2JSabWM3aw9FAwXv", "HNL7i8NUQ9ew1xudEdonmhRF4mHYdVEl");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("asr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            AsrClient client = new AsrClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SentenceRecognitionRequest req = new SentenceRecognitionRequest();
            req.setEngSerViceType("16k_zh");
            req.setSourceType(1L);
            req.setVoiceFormat("m4a");
            req.setData(data);
            req.setDataLen(Integer.toUnsignedLong(bytes.length));
            // 返回的resp是一个SentenceRecognitionResponse的实例，与请求对象对应
            SentenceRecognitionResponse resp = client.SentenceRecognition(req);
            // 输出json格式的字符串回包
             resultTxt =resp.getResult();

        } catch (
                TencentCloudSDKException e) {
            log.error("文本转语音错误{}",e.toString());
        }
        return resultTxt;
    }

    private CommonRequest buildRequest(String popApiName) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("nls-slp.cn-shanghai.aliyuncs.com");
        request.setVersion("2019-08-19");
        request.setAction(popApiName);
        request.setProtocol(ProtocolType.HTTPS);
        return request;
    }

    private String sendRequest(CommonRequest request) {
        try {
            CommonResponse response = getIAcsClient().getCommonResponse(request);
            return response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    private NlsClient getNlsClient() {
        if (nlsClient == null) {
            String token = aliYunService.getAccessToken();
            String url = "wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1";

            nlsClient = new NlsClient(url, token);
        }

        return nlsClient;
    }

    private IAcsClient getIAcsClient() {
        if (iAcsClient == null) {
            // 创建DefaultAcsClient实例并初始化
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai", "LTAI5t6rV2sRnzL5p1WpAQse"
                    ,
                    "lqns8N8N7C4FqGYniJbC5ERHrIM0hx");
            iAcsClient = new DefaultAcsClient(profile);
        }
        return iAcsClient;

    }

    public static void main(String[] args) {
        try {
            byte[] bytes= FileUtil.readBytes("C:/Users/g6286/Desktop/1.mp3");
            String data=Base64.getEncoder().encodeToString(bytes);
             Credential cred = new Credential("AKIDJVXQ6ZqdEb0FKG1c2JSabWM3aw9FAwXv", "HNL7i8NUQ9ew1xudEdonmhRF4mHYdVEl");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("asr.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            AsrClient client = new AsrClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SentenceRecognitionRequest req = new SentenceRecognitionRequest();
            req.setEngSerViceType("16k_zh");
            req.setSourceType(1L);
            req.setVoiceFormat("mp3");
            req.setData(data);
            req.setDataLen(88380L);
            // 返回的resp是一个SentenceRecognitionResponse的实例，与请求对象对应
            SentenceRecognitionResponse resp = client.SentenceRecognition(req);
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
        } catch (
                TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
    }


}
